import express, { Request, Response, NextFunction, Application } from 'express';
import cors from 'cors';
import path from 'path';
import dotenv from 'dotenv';
import swaggerUi from 'swagger-ui-express';
import { swaggerSpec } from './config/swagger';
import { StockDataCrawler } from './services/StockDataCrawler';

// 根据 NODE_ENV 加载对应的环境文件
const envFile = process.env.NODE_ENV === 'production' ? '.env.production' : '.env';
dotenv.config({ path: envFile });

const app: Application = express();
const PORT: number = parseInt(process.env.PORT || '3129', 10);

// 中间件配置
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// API路由
import stockRoutes from './routes/stocks';
import authRoutes from './routes/auth';

/**
 * @swagger
 * /health:
 *   get:
 *     summary: 健康检查接口
 *     description: 检查服务器运行状态
 *     tags: [System]
 *     responses:
 *       200:
 *         description: 服务器正常运行
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 status:
 *                   type: string
 *                   example: "ok"
 *                 timestamp:
 *                   type: string
 *                   format: date-time
 *                   example: "2025-09-06T03:17:47.660Z"
 *                 uptime:
 *                   type: number
 *                   example: 123.456
 */
app.get('/health', (req: Request, res: Response): void => {
  res.json({
    status: 'ok',
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

// Swagger API文档
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, {
  explorer: true,
  customSiteTitle: '股票分析服务系统 API 文档',
  customCss: '.swagger-ui .topbar { display: none }',
  customfavIcon: '/favicon.ico'
}));

// API文档JSON
app.get('/api-docs.json', (req: Request, res: Response): void => {
  res.json(swaggerSpec);
});

// 认证相关API
app.use('/api/auth', authRoutes);

// 股票相关API
app.use('/api/stocks', stockRoutes);

// 404处理
app.use('*', (req: Request, res: Response): void => {
  res.status(404).json({
    success: false,
    message: '接口不存在'
  });
});

// 全局错误处理中间件
app.use((err: Error, req: Request, res: Response, _next: NextFunction): void => {
  console.error('服务器错误:', err);
  
  // 开发环境返回详细错误信息
  if (process.env.NODE_ENV === 'development') {
    res.status(500).json({
      success: false,
      message: err.message,
      stack: err.stack
    });
  } else {
    // 生产环境返回通用错误信息
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

// 启动服务器
function startServer(): void {
  try {
    app.listen(PORT, '0.0.0.0', (): void => {
      console.log(`🚀 服务器启动成功`);
      console.log(`📍 本地访问: http://localhost:${PORT}`);
      console.log(`📍 外网访问: http://0.0.0.0:${PORT}`);
      console.log(`🌍 环境: ${process.env.NODE_ENV || 'development'}`);
      console.log(`📊 健康检查: http://localhost:${PORT}/health`);
      console.log(`📚 API文档: http://localhost:${PORT}/api-docs/`);
      console.log(`📚 外网API文档: http://[your-server-ip]:${PORT}/api-docs/`);
      console.log(`🔧 API文档JSON: http://localhost:${PORT}/api-docs.json`);
      
      // 启动股票数据爬虫
      const stockCrawler = new StockDataCrawler();
      stockCrawler.start();
    });
  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
}

// 优雅关闭
process.on('SIGTERM', (): void => {
  console.log('收到SIGTERM信号，正在关闭服务器...');
  process.exit(0);
});

process.on('SIGINT', (): void => {
  console.log('收到SIGINT信号，正在关闭服务器...');
  process.exit(0);
});

startServer();

export default app;